#ifndef SOUNDOUT_H
#define SOUNDOUT_H

#include <QtCore>
#include <QAudioDeviceInfo>
#include <QAudioOutput>

#define BUFFERSIZE 32768

// An instancs of this thread sends audio data to a specified soundcard.
// Output can be muted while underway, preserving waveform timing when the
// mute is canceled.

class SoundOutThread : public QThread
{
  Q_OBJECT

protected:
  virtual void run();

public:
// Constructs (but does not start) a SoundOutThread
  SoundOutThread()
  // Initialize a number of private members:
    :   m_pushTimer(new QTimer(this))
    ,   m_device(QAudioDeviceInfo::defaultOutputDevice())
    ,   m_audioOutput(0)
    ,   m_output(0)
    ,   m_buffer(BUFFERSIZE, 0)
    ,   m_zeros(BUFFERSIZE, 0)
    ,   m_npts(0)
    ,   m_samplesWritten(0)
    ,   m_txData(0)
    ,   m_txMute(false)
    ,   m_rate(0)
  {
  }

// Public functions
  void setOutputDevice(const QAudioDeviceInfo& outputDevice);
  void setRate(double rate);
  void play(qint16 *wave, qint64 npts);
  void abort();
  void txMute();

// Private members
private:
  QTimer*          m_pushTimer;
  QAudioDeviceInfo m_device;
  QAudioOutput*    m_audioOutput;
  QIODevice*       m_output;
  QAudioFormat     m_format;
  QByteArray       m_buffer;
  QByteArray       m_zeros;
  qint64           m_npts;
  qint64           m_samplesWritten;
  char*            m_txData;
  bool             m_txMute;
  double           m_rate;                                    // sample rate

private slots:
  void pushTimerExpired();
};

#endif
